<?php
class Ecore_Cache
{
	public static $groupkey 	= '';
	public static $cache 		= null;
	public static $clear 		= null;
	public static $compression = true;

	public function __construct() {
		if(USE_MEMCACHED) {
			$objConf = new Zend_Config_Ini(ROOT_DIR . '/configs/config.ini', 'memcache');
			$objCache = new Memcache;
			foreach ($objConf as $cache=>$config) {
				$arrCacheConf = $config->toArray();			
				$objCache->addServer($arrCacheConf['host'], $arrCacheConf['port'], $arrCacheConf['persistent']);
			}
		} else {
			$objCache = null;
		}
		$strDeleteClass	= 'Ecore_Cache_' . ucfirst(str_replace('/','',FRONTEND_NAME));			
		$this->cache	= $objCache;
		$this->clear 	= new $strDeleteClass($this);		
		$this->groupkey = '';
		
	}
	public function setGroupKey($strGroupKey = '') {
		if(USE_MEMCACHED) {
			if ($strGroupKey) {
				$this->groupkey = $strGroupKey;
				$arrGroupKey = $this->cache->get($this->groupkey);
				if (!$arrGroupKey) {
					$this->cache->set($this->groupkey, array(), false, 0);			
				}
			}
		}
	}
	
	public function deleteKeyCached(){
		if(USE_MEMCACHED) {
			if ($this->groupkey) {
				$this->cache->set($this->groupkey, array(), false, 0);
			}
		}
	}
	
	public function updateKeyCached($arrGroupKey = array()) {
		if(USE_MEMCACHED) {
			if ($this->groupkey) {			
				$this->cache->set($this->groupkey, $arrGroupKey, false, 0);			
			}
		}
	}
	
	public function getKeyCached(){
		if(USE_MEMCACHED) {
			if ($this->groupkey)  {
				$arrGroupKey = $this->get($this->groupkey);
				return $arrGroupKey;
			}
			return null;
		}
	}

	public function get($key) {
		if(USE_MEMCACHED) {	
			//return Zend_Json::decode($this->cache->get($key));			
		}
		return null;
	}

	public function set($key, $data, $expire = 0) {
		if(USE_MEMCACHED) {	
			//$data = Zend_Json::encode($data);	
			if (!$data) {
				$data = NOCACHE;
			} elseif ($this->groupkey)  {				
				$arrGroupKey = $this->cache->get($this->groupkey);
				if (!in_array($key, $arrGroupKey)) {
					$arrGroupKey[] = $key;
					$this->cache->set($this->groupkey, $arrGroupKey, false, 0);
				}
			}
			return $this->cache->set($key, $data, false, $expire);
		}
		return 0;
	}

	public function delete($key) {
		if(USE_MEMCACHED) {	
			$key = is_array($key) ? $key : array($key);
			foreach ($key as $k=>$id) {
				$this->cache->delete($id);
			}
		}
	}

	public function flush()	{
		if(USE_MEMCACHED) {	
			return $this->cache->flush();
		}
	}
}
?>